/**
 * Copyright © 2014 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.rayson.share.http;


/**
 * TODO Add type description here.
 *
 * @author creativor
 */
public class HttpMessageParser {
	/**
	 * Copy byte array from source byte array.
	 * 
	 * @param src
	 *            Source byte array.
	 * @param fromIndex
	 *            Copy from index.
	 * @param toIndex
	 *            Copy to byte index. Excluded.
	 * @return new copied byte array.
	 */
	protected static byte[] copy(final byte[] src, final int fromIndex,
			final int toIndex) {
		final byte[] result = new byte[toIndex - fromIndex];
		for (int i = 0; i < result.length; i++) {
			result[i] = src[fromIndex + i];
		}
		return result;
	}

	/**
	 * @param line
	 * @return
	 */
	public static HttpHeader parseHeader(final byte[] line) {

		int pos = 0;
		final int nameIndex = search(line, pos,
				(byte) HttpConstants.MESSAGE_HEADER_SPLITER);
		// if (nameIndex <= 0)
		// throw new HttpProtocolException("Header line format is wrong");
		final String name = new String(copy(line, pos, nameIndex));

		pos = nameIndex + 2;
		// if (pos >= line.length - 2)
		// throw new HttpProtocolException("Header line format is wrong");
		final String value = new String(copy(line, pos, line.length - 2));
		return new HttpHeader(name, value);

	}

	public static HttpRequestLine parseRequestLine(final byte[] line) {

		final byte key = HttpConstants.SPACE;
		int pos = 0;
		int index = search(line, pos, key);
		// if (index < 0)
		// throw new HttpProtocolException("Request line format is wrong");
		final String methodStr = new String(copy(line, pos, index));

		HttpMethod method = null;
		try {
			method = HttpMethod.valueOf(methodStr);

		} catch (final Exception e) {

			// throw new HttpProtocolException("Unsupported method " +
			// methodStr);
		}

		pos = index + 1;
		index = search(line, pos, key);
		// if (index < 0 || index >= line.length)
		// throw new HttpProtocolException("Request line format is wrong");
		final String uri = new String(copy(line, pos, index));

		pos = index + 1;
		final String version = new String(copy(line, pos, line.length - 2));

		return new HttpRequestLine(method, uri.toString(), version.toString());

	}

	/**
	 * Search a key byte from source byte array. Begin from the start index.
	 * 
	 * @return First matched byte index.Or -1, if no key byte found.
	 */
	protected static int search(final byte[] src, final int startIndex,
			final byte key) {
		final int result = -1;
		for (int i = startIndex; i < src.length; i++) {
			if (src[i] == key)
				return i;

		}
		return result;
	}
}